/**
 * @Description: 在线资源专栏
 * @author ourslookAdmin
 * @date 2019-08-28 09:32:29
 */
import React, {Fragment} from 'react';
import 'braft-editor/dist/index.css';
import Modal from 'drag-modal';
import BraftEditor from 'braft-editor';
import {
  Button,
  Card,
  Checkbox,
  Col,
  Divider,
  Form,
  Input,
  InputNumber,
  Radio,
  Row,
  Select,
  Spin,
  Tag,
  TreeSelect,
  BackTop, Tooltip, Icon, Upload,
} from 'antd';
import {formatMessage, FormattedMessage} from 'umi/locale';
import 'antd/dist/antd.css';
import PropTypes from 'prop-types';
import {connect} from 'dva';
import {requestLists, requestPromise} from '@/utils/request';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import BaseForm from '../../../components/ourslook/BaseForm';
import ETable from '../../../components/ourslook/ETable';
import {getWebPath} from '../../../utils/request';
import uiUtils, {hasPermission, rulesReg, rulesRemote} from '../../../utils/uiUtils';
import styles from '../../../utils/ourslook.less';
import DefaultImage from '../../../components/ourslook/DefaultImage';
import {handleEditorupload, editorPreview, editorProps} from "../../../utils/braft_editor_config";


const FormItem = Form.Item;
const Option = Select.Option;
const RadioGroup = Radio.Group;
const TextArea = Input.TextArea;
const Password = Input.Password;
const CheckboxGroup = Checkbox.Group;

const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');

@connect(() => ({}))
class BusOnlineResColumn extends React.Component {
  params = {
    page: 1,
    limit: 10,
  };

  formItemLayout = {
    labelCol: {span: 5},
    wrapperCol: {span: 19},
  };

  /**
   * https://ant-design.gitee.io/components/table-cn/
   *
   * 需要指定 column 的 width 属性，否则列头和内容可能不对齐。（必须留一列不设宽度或者minWidth以适应弹性布局）
   * 建议指定 scroll.x 为大于表格宽度的固定值或百分比。注意，且非固定列宽度之和不要超过 scroll.x, 一般无table正常展开的宽度
   * 未知长度字段或者字符特别多的字段不要放置在列表
   */
  columns = [
    {
      title: '',
      width: 30,
      align: 'center',
      fixed: 'left',
      render: (value, record, index) => index + 1,
    },
    {title: '专栏名称', dataIndex: 'columnName', align: 'center', sorter: false, key: 'column_name'},
    {
      title: '资源类型',
      dataIndex: 'resType',
      width: 100,
      align: 'center',
      sorter: false,
      render: val => {
        let type = '';
        if (val === 1) {
          type = '视频';
        } else if (val === 2) {
          type = '音频';
        }
        return type;
      },
    },
    {
      title: '专栏首图',
      dataIndex: 'columnCover',
      align: 'center',
      width: 100,
      sorter: false,
      render: record => <DefaultImage src={record} />,
    },
    {
      title: '微信二维码',
      dataIndex: 'wxQrCode',
      width: 100,
      align: 'center',
      sorter: false,
      render: (value, record, index) =>
        value === undefined ? (
          <Tag style={{ cursor: 'default' }} className={styles.label_primary}>
            未生成
          </Tag>
        ) : (
          <Tag style={{ cursor: 'default' }} className={styles.label_success}>
            已生成
          </Tag>
        ),
    },
    {title: '创建时间', dataIndex: 'createTime', width: 190, align: 'center', sorter: true, key: 'create_time'},
    {
      title: '操作',
      dataIndex: '',
      width: 180,
      align: 'center',
      fixed: 'right',
      render: (value, record, index) => (
        <React.Fragment>
          <a
            hidden={!hasPermission('busonlinerescolumn:update')}
            onClick={() => {
              this.setStateByTableColume(record, index);
              this.update();
            }}
          >
            <Tooltip title={<FormattedMessage id="ours.curd.list.edit" defaultMessage="编辑" />}>
              <Icon type="edit" />
            </Tooltip>
          </a>
          <Divider type="vertical" />
          <a
            hidden={!hasPermission('busonlinerescolumn:info')}
            onClick={() => {
              this.setStateByTableColume(record, index);
              this.view();
            }}
          >
            <Tooltip title={<FormattedMessage id="ours.curd.list.info" defaultMessage="查看" />}>
              <Icon type="info" />
            </Tooltip>
          </a>

          <Divider type="vertical" />

          <a
            hidden={!hasPermission('busonlinerescolumn:info')}
            onClick={() => {
              this.createWxImage(record, index);
            }}
          >
            <Tooltip
              title={
                <FormattedMessage id="ours.curd.list.createWxImage" defaultMessage="生成二维码" />
              }
            >
              <Icon type="file-image" />
            </Tooltip>
          </a>
        </React.Fragment>
      ),
    },
  ];

  constructor(props) {
    super(props);
    this.state = {
      showList: 1, //1:显示列表、2:显示新增
      formList: BusOnlineResColumn.getFormList(),
      selectedRows: [],
      selectedIds: [],
      selectedIndexs: [],
      editModalTitle: null,
      editModalType: null,
      editModel: null,
      editModelConfirmLoading: false,
      //其他属性下面书写
    };
  }

  // 筛选条件
  static getFormList = () => [
    {
      type: 'INPUT',
      field: 'columnName',
      label: '专栏名称',
      placeholder: '专栏名称',
    },
    {
      type: 'SELECT',
      field: 'resType',
      label: '资源类型',
      placeholder: '资源类型',
      initialValue: '',
      list: [{ id: '', name: '请选择类型' }, { id: '1', name: '视频' }, { id: '2', name: '音频' }],
    },
  ];

  componentDidMount() {
    this.requestList();
  }

  componentWillUnmount() {
  }

  /**
   * 根据 formItem field 取值 查找formItem
   * @param formItemField obj的field字段
   * @returns 一个对象
   */
  findFormListItemByField = formItemField =>
    this.state.formList.find((value, index, array) => value.field === formItemField);

  query = fieldParams => {
    this.params = JSON.parse(JSON.stringify(Object.assign(this.params, fieldParams)));
    this.requestList();
  };

  add = () => {
    this.setState({
      editModalType: 'add',
      editModalTitle: formatMessage({id: 'ours.curd.list.create'}), //创建
      editModel: {},
      showList: 2,
    });
  };

  update = () => {
    const {selectedRows, selectedIds, selectedIndexs} = this.state;
    if (!selectedRows) {
      uiUtils.showAlert(formatMessage({id: 'ours.curd.show-alert.select-please'}));
      return;
    }
    if (selectedRows.length > 1) {
      uiUtils.showAlert(formatMessage({id: 'ours.curd.show-alert.select-one-please'}));
      return;
    }
    this.setState({
      editModalType: 'update',
      editModalTitle: <FormattedMessage id="ours.curd.list.edit" defaultMessage="编辑"/>,
      editModel: JSON.parse(JSON.stringify(selectedRows[0])),
      showList: 2,
    });
    this.getInfo(selectedRows[0].id);
  };

  view = () => {
    const {selectedRows, selectedIds, selectedIndexs} = this.state;
    if (!selectedRows) {
      uiUtils.showAlert(formatMessage({id: 'ours.curd.show-alert.select-please'}));
      return;
    }
    if (selectedRows.length > 1) {
      uiUtils.showAlert(formatMessage({id: 'ours.curd.show-alert.select-one-please'}));
      return;
    }
    this.setState({
      editModalType: 'view',
      editModalTitle: <FormattedMessage id="ours.curd.list.info" defaultMessage="查看"/>,
      editModel: selectedRows[0],
      showList: 2,
    });
    this.getInfo(selectedRows[0].id);
  };

  createWxImage = (record, index) => {
    //此处如果它的类型值为空， 为了不让下面的接口出现异常，这里传入-1， -1 在接口中也代表该值不存在
    if (record.wxQrCode) {
      uiUtils.showConfirm(formatMessage({ id: '已经存在二维码，是否再次生成？' }), () => {
        requestPromise(
          `${getWebPath(
            `/busonlinerescolumn/createWxImage?id=${record.id}&resType=${record.resType}`
          )}`,
          {
            method: 'GET',
          }
        ).then(res => {
          if (res && res.code === 0) {
            uiUtils.showMessage('操作成功');
            this.requestList();
          }
        });
      });
    } else {
      uiUtils.showConfirm(formatMessage({ id: '是否生成二维码？' }), () => {
        requestPromise(
          `${getWebPath(
            `/busonlinerescolumn/createWxImage?id=${record.id}&resType=${record.resType}`
          )}`,
          {
            method: 'GET',
          }
        ).then(res => {
          if (res && res.code === 0) {
            uiUtils.showMessage('操作成功');
            this.requestList();
          }
        });
      });
    }
  };

  del = () => {
    const selectedRows = this.state.selectedRows;
    const ids = [];
    for (let i = 0; i < selectedRows.length; i += 1) {
      ids.push(selectedRows[i].id);
    }

    uiUtils.showConfirm(formatMessage({id: 'ours.curd.show-alert.confirm-delete'}), () => {
      this.setState({
        loading: true,
      });
      requestPromise(`${getWebPath()}busonlinerescolumn/delete`, {
        method: 'POST',
        body: ids,
      }).then(res => {
        this.setState({
          loading: false,
        });
        if (res && res.code === 0) {
          uiUtils.showMessage(
            formatMessage({id: 'ours.curd.show-alert.operate-success'}),
            'success'
          );
          this.requestList();
        }
      });
    });
  };

  saveOrUpdate = () => {
    const editModalType = this.state.editModalType;
    //不能双向绑定，这里只能原对象、新对象进行合并.
    const busOnlineResColumn = Object.assign(this.state.editModel, this.editForm.props.form.getFieldsValue());

    this.editForm.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        // submit the values
        const url = busOnlineResColumn.id == null ? '/busonlinerescolumn/save' : '/busonlinerescolumn/update';
        //对象删除一个属性
        //delete busOnlineResColumn.xxxxPros;

        busOnlineResColumn.columnDetails = busOnlineResColumn.columnDetails.toHTML();

        let columnImgs = '';
        for (let i = 0; i < this.editForm.state.columnImgsList.length; i += 1) {
          let item = '';
          if(i === this.editForm.state.columnImgsList.length-1){
            item = this.editForm.state.columnImgsList[i].response.object;
          }else{
            item = `${this.editForm.state.columnImgsList[i].response.object},`;
          }
          columnImgs += item;
        }
        busOnlineResColumn.columnImgs = columnImgs;

        this.setState({
          editModelConfirmLoading: true,
        });
        requestPromise(getWebPath() + url, {
          method: 'POST',
          body: busOnlineResColumn,
        }).then(res => {
          this.setState({
            editModelConfirmLoading: false,
          });
          if (res && res.code === 0) {
            uiUtils.showMessage(
              formatMessage({id: 'ours.curd.show-alert.operate-success'}),
              'success'
            );
            this.setState({
              showList: 1,
            });

            //新增重新置为第一页
            if (!busOnlineResColumn.id) {
              this.params.page = 1;
            }
            this.requestList();
          }
        });
      }
    });
  };

  getInfo = id => {
  };

  setStateByTableColume = (record, index) => {
    this.state = {
      ...this.state,
      selectedRows: [record],
      selectedIds: [record.id],
      selectedIndexs: [index],
    };
  };

  operateByIds = (status) => {
  };

  //========其他所有的处理方法，请在按照约定进行处理==========


  /**
   * 表格 筛选和排序 回调
   */
  filtersSorterChange = tableParams => {
    this.params = JSON.parse(JSON.stringify(Object.assign(this.params, tableParams)));
    this.requestList();
  };

  requestList = () => {
    requestLists(this, `${getWebPath()}busonlinerescolumn/list`, this.params);
  };

  vShow = showListNum => ({display: this.state.showList === showListNum ? 'block' : 'none'});

  render() {
    const style = {
      style: {
        marginLeft: 10,
        marginTop: 10,
      },
      disabled: this.state.selectedIndexs.length <= 0,
    };

    /* eslint-disable react/jsx-no-bind */
    return (
      <PageHeaderWrapper title="">
        <Card
          bordered={false}
          style={{...this.vShow(1)}}
          className={styles.oursCard}
          bodyStyle={{padding: '20px'}}
        >
          <BaseForm
            formList={this.state.formList}
            loading={this.state.loading}
            filterSubmit={this.query}
          />

          <Fragment>
            <Button
              type="primary"
              icon="plus"
              onClick={this.add}
              hidden={!hasPermission('busonlinerescolumn:save')}
            >
              <FormattedMessage id="ours.curd.list.add" defaultMessage="新增"/>
            </Button>
            <Button
              type="danger"
              icon="delete"
              {...style}
              onClick={this.del}
              hidden={!hasPermission('busonlinerescolumn:delete')}
            >
              <FormattedMessage id="ours.curd.list.delete" defaultMessage="删除"/>
            </Button>
          </Fragment>

          <div className="content-wrap">
            <ETable
              onSelectRow={uiUtils.onSelectRow.bind(this)}
              primaryKey="id"
              selectedIndexs={this.state.selectedIndexs}
              selectedRows={this.state.selectedRows}
              selectedIds={this.state.selectedIds}
              onChange={this.filtersSorterChange}
              columns={this.columns}
              dataSource={this.state.list}
              pagination={this.state.pagination}
              loading={this.state.loading}
              scroll={{x: 900}}
            />
          </div>
        </Card>

        <BackTop/>

        <Spin spinning={this.state.editModelConfirmLoading} delay={10}>
          {//返回null,这里对不用的组件进行销毁
            this.state.showList === 1 ? null : (
              <Card
                title={this.state.editModalTitle}
                bordered={false}
                actions={[
                  <div>
                    <React.Fragment>
                      <Button
                        type="primary"
                        hidden={this.state.editModalType === 'view'}
                        style={{marginRight: '18px'}}
                        onClick={this.saveOrUpdate}
                      >
                        <FormattedMessage id="ours.curd.add.save" defaultMessage="保存"/>
                      </Button>
                      <Button
                        style={{marginRight: '18px'}}
                        onClick={() => {
                          this.editForm.props.form.resetFields();
                          this.setState({showList: 1});
                        }}
                      >
                        <FormattedMessage id="ours.curd.add.back" defaultMessage="返回"/>
                      </Button>
                    </React.Fragment>
                  </div>,
                ]}
                style={{...this.vShow(2)}}
                bodyStyle={{padding: '20px'}}
                ref={node => {
                  this.container = node;
                }}
              >
                <EditForm
                  type={this.state.editModalType}
                  model={this.state.editModel}
                  wrappedComponentRef={inst => {
                    this.editForm = inst;
                  }}
                />
              </Card>
            )}
        </Spin>
      </PageHeaderWrapper>
    );
  }
}

export default BusOnlineResColumn;

/**
 *  新增、编辑、复制、查看的Form
 */

/* eslint react/no-multi-comp:0 */
class EditForm extends React.Component {

  static propTypes = {
    type: PropTypes.string, //form类型，可选值：add（增加）、update（修改）、copy（复制）、view（查看）、
    model: PropTypes.object, //数据模型model，对应后台的model
  };

  static defaultProps = {
    type: '', //表单布局数组
    model: null,
  };

  constructor(props) {
    super(props);
    const defaultImgList = this.props.model.columnCover
      ? [
        {
          uid: '1',
          name: '',
          status: 'done',
          type: 'image/',
          url: this.props.model.columnCover,
          response: {
            object: this.props.model.columnCover,
          },
        },
      ]
      : null; //defaultFileList
    const defaultcolumnImgsList = this.getDefaultcolumnImgsList();
    this.state = {
      previewImgVisible: false, //上传文件预览
      previewImg: '', //上传文件预览
      defaultImgList, //上传文件列表
      imgList: defaultImgList && defaultImgList.length > 0 ? [defaultImgList[0]] : [],
      defaultcolumnImgsList, //上傳文件列表
      columnImgsList: defaultcolumnImgsList && defaultcolumnImgsList.length > 0 ? defaultcolumnImgsList : [],
      previewcolumnImgsVisible: false, //上傳文件預覽
      previewcolumnImgs: '', //上傳文件預覽
    };
  }

  /**
   * 生命周期-属性发生变化...componentWillReceiveProps
   * 这里的nextProps，可以获取到所有的属性。
   * 目前没用，因为 dialog 每次都被销毁了
   */
  componentWillReceiveProps(nextProps) {}

  getPropsByKey = prop => {
    const model = this.props.model || {};
    const finalModel = Object.assign(model, this.props.form.getFieldsValue());
    return finalModel[prop];
  };

  preview = () => {
    editorPreview(this.state.editorState.toHTML());
  };

  handleUploadImgOnChange = info => {
    const { loadingCallback } = this.props;
    // 状态有：uploading done error removed
    if (info.file.status === 'done') {
      //这个Upload组件比较特殊，这里在OnChange方法手工设置value,不做延迟，就设置不了被覆盖了。
      const response = info.fileList[0].response;
      this.setState({
        imgList: info.fileList,
      });
      if (response) {
        if (response.code === 0) {
          uiUtils.showMessage(`${info.file.name} 文件上传成功.`, 'success');
          setTimeout(() => {
            this.props.form.setFieldsValue({
              columnCover: response.object,
            });
            if (loadingCallback) {
              loadingCallback(false);
            }
          }, 500);
        } else {
          uiUtils.showAlert(response.msg, 'error');
          if (loadingCallback) {
            loadingCallback(false);
          }
        }
      }
    } else if (info.file.status === 'error') {
      if (loadingCallback) {
        loadingCallback(false);
      }
      uiUtils.showMessage(`${info.file.name} 文件上传失败.`, 'error');
    } else if (info.file.status === 'uploading') {
      if (loadingCallback) {
        loadingCallback(true);
      }
    }
  };

  handleUploadImgOnRemove = file => {
    //只上传一文件，这里偷懒
    this.setState({
      imgList: [],
      defaultImgList: null,
    });
    this.props.form.setFieldsValue({
      columnCover: "",
    });
  };

  handleUploadImgPreview = file => {
    const previewImg = file.url || file.thumbUrl;
    const previewImgVisible = true;
    this.setState({
      previewImg,
      previewImgVisible,
    });
  };

  handleUploadcolumnImgsImageOnChange = info => {
    const {loadingCallback} = this.props;
    // 狀態有：uploading done error removed
    if (info.file.status === 'done') {
      uiUtils.showMessage(`${info.file.name} 文件上傳成功.`, 'success');
      //這個Upload組件比較特殊，這裏在OnChange方法手工設置value,不做延遲，就設置不了被覆蓋了。
      const response = info.fileList[0].response;
      this.setState({
        columnImgsList: info.fileList,
      });
      if (response) {
        if (response.code === undefined || response.code === 0) {
          setTimeout(() => {
            this.props.form.setFieldsValue({
              columnImgs: response.object,
            });
            if (loadingCallback) {
              loadingCallback(false);
            }
          }, 500);
        } else {
          uiUtils.showAlert(response.msg, 'error');
          if (loadingCallback) {
            loadingCallback(false);
          }
        }
      }
    } else if (info.file.status === 'error') {
      if (loadingCallback) {
        loadingCallback(false);
      }
      uiUtils.showMessage(`${info.file.name} 文件上傳失敗.`, 'error');
    } else if (info.file.status === 'uploading') {
      if (loadingCallback) {
        loadingCallback(true);
      }
    }
  };

  handleUploadcolumnImgsImageOnRemove = file => {
    const {columnImgsList: newcolumnImgsList} = this.state;
    for (let i = 0; i < newcolumnImgsList.length; i += 1) {
      if (file.uid === newcolumnImgsList[i].uid) {
        newcolumnImgsList.splice(i, 1);
        i -= 1;
        break;
      }
    }
    this.setState({
      columnImgsList: newcolumnImgsList,
      defaultcolumnImgsList: null,
    });
    if (newcolumnImgsList.length === 0) {
      this.props.form.setFieldsValue({
        columnImgs: "",
      });
    }
  };

  handledefaultcolumnImgsPreview = file => {
    const previewcolumnImgs = file.url || file.thumbUrl;
    const previewcolumnImgsVisible = file.type.startsWith('image/');
    this.setState({
      previewcolumnImgs,
      previewcolumnImgsVisible,
    });
  };

  getDefaultcolumnImgsList = () => {
    let defalutIcons = null;
    if (this.props.model.columnImgs) {
      defalutIcons = [];
      for (let i = 0; i < this.props.model.columnImgs.split(',').length; i += 1) {
        defalutIcons.push({
          uid: i + 1,
          name: '',
          status: 'done',
          type: 'image/',
          url: this.props.model.columnImgs.split(',')[i],
          response: {
            object: this.props.model.columnImgs.split(',')[i],
          },
        });
      }
    }
    return defalutIcons;
  };

  render() {
    const type = this.props.type; //编辑是：新增（add）、编辑(edit)、复制(copy)、还是查看(view)
    const model = this.props.model || {};
    const {form, form: {getFieldDecorator, getFieldValue, setFieldsValue}} = this.props;
    const formItemLayout = {
      labelCol: {span: 5},
      wrapperCol: {span: 18}, //5+19=24,少一个栅格
    };
    const colSpanLayout = {md: 12, sm: 24}; //每一col跨?列
    const rowGutterPxLayout = {md: 24, sm: 16}; //col之间的间隔?px
    const inputCodeDisabled = {
      disabled: type === 'update',
    };
    const extendControls = [
      {
        key: 'custom-button',
        type: 'button',
        text: '预览',
        onClick: this.preview,
      },
    ];

    const inputCodeDisabledForView = {
      disabled: type === 'view',
    };
    const columnCoverProps = {
      action: `${getWebPath('/api/fileUpload')}`,
      name: 'myfile',
      data: { moduleName: 'onlinecolumn', isImage: true, acceptFileExts: 'image' },
      withCredentials: true,
      headers: {
        authorization: 'authorization-text',
      },
      onChange: this.handleUploadImgOnChange,
      onRemove: this.handleUploadImgOnRemove,
      defaultFileList: this.state.defaultImgList,
      multiple: false,
      accept: '.jpg, .jpeg, .png, .bmp, ',
    };
    const columnImgsProps = {
      action: `${getWebPath('/api/fileUpload')}`,
      name: 'myfile',
      data: {moduleName: 'onlinecolumn', isImage: true, acceptFileExts: 'image'},
      withCredentials: true,
      headers: {
        authorization: 'authorization-text',
      },
      onChange: this.handleUploadcolumnImgsImageOnChange,
      onRemove: this.handleUploadcolumnImgsImageOnRemove,
      defaultFileList: this.state.defaultcolumnImgsList,
      multiple: false,
      accept: '.jpg, .jpeg, .png, .bmp, ',
    };
    const uploadButton = (
      <div>
        <Icon type="plus" />
        <div className="ant-upload-text">上传</div>
      </div>
    );

    //校验文档：https://ant.design/components/form-cn/#%E6%A0%A1%E9%AA%8C%E8%A7%84%E5%88%99
    return (
      <Form layout="horizontal">
        <Row gutter={{...rowGutterPxLayout}}>
          <Col {...colSpanLayout}>
            <FormItem label="专栏名称" {...formItemLayout}>
              {type === 'view'
                ? model.columnName
                : getFieldDecorator('columnName', {
                  initialValue: model.columnName,
                  rules: [
                    {
                      required: true,
                      message: '专栏名称必填',
                    },
                    {
                      max: 64,
                      message: '最长64个字符',
                    },
                  ],
                })(
                  <Input
                    type="text"
                    autocomplete="off"
                    placeholder="专栏名称"
                  />
                )}
            </FormItem>
          </Col>
          <Col {...colSpanLayout}>
            <FormItem label="资源类型" {...formItemLayout}>
              {type === 'view'
                ? model.resType === 1
                  ? '视频'
                  : '音频'
                : getFieldDecorator('resType', {
                  initialValue: model.resType,
                  rules: [
                    {
                      required: true,
                      message: '资源类型必填',
                    },
                  ],
                })(
                  <Select
                    {...inputCodeDisabled}
                    defaultValue="音频"
                    placeholder="请选择"
                    style={{ width: '100%' }}
                  >
                    <Option value={1}>视频</Option>
                    <Option value={2}>音频</Option>
                  </Select>
                )}
            </FormItem>
          </Col>
          <Col {...colSpanLayout}>
            <FormItem label="专栏标签" {...formItemLayout}>
              {type === 'view'
                ? model.columnTags
                : getFieldDecorator('columnTags', {
                  initialValue: model.columnTags,
                })(
                  <Input
                    type="text"
                    autocomplete="off"
                    placeholder="专栏标签 多个英文逗号分割"
                  />
                )}
            </FormItem>
          </Col>
          <Col {...colSpanLayout}>
            <FormItem label="微信二维码" {...formItemLayout}>
              {getFieldDecorator('wxQrCode', {
                initialValue: model.wxQrCode,
                rules: [],
              })(
                <div className="clearfix">
                  <DefaultImage style={{ width: '50%', height: '50%' }} src={model.wxQrCode} />
                </div>
              )}
            </FormItem>
          </Col>
          <Col {...colSpanLayout}>
            <FormItem
              label="专栏首图"
              extra="支持png、jpg、gif, 大小不超过3MB, 推荐尺寸：291X271;"
              {...formItemLayout}
            >
              {getFieldDecorator('columnCover', {
                initialValue: model.columnCover,
                rules: [
                  {
                    required: true,
                    message: '专栏首图必上传',
                  },
                ],
              })(
                <div className="clearfix">
                  <Upload
                    {...columnCoverProps}
                    listType="picture-card"
                    onPreview={this.handleUploadImgPreview}
                  >
                    {this.state.imgList && this.state.imgList.length >= 1 ? null : uploadButton}
                  </Upload>
                  <Modal
                    visible={this.state.previewImgVisible}
                    footer={null}
                    onCancel={() => this.setState({ previewImgVisible: false })}
                  >
                    <img
                      alt="imgExample"
                      style={{ width: '100%' }}
                      src={this.state.previewImg}
                    />
                  </Modal>
                </div>
              )}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{...rowGutterPxLayout}}>
          <Col {...colSpanLayout}>
            <FormItem
              label="专栏详情图"
              extra="支持png、jpg、gif, 大小不超过3MB, 推荐尺寸：690X231;"
              {...formItemLayout}
            >
              {getFieldDecorator('columnImgs', {
                initialValue: model.columnImgs,
                rules: [
                  {
                    required: true,
                    message: '专栏详情图必上传',
                  },
                ],
              })(
                <div className="clearfix">
                  <Upload
                    {...columnImgsProps}
                    listType="picture-card"
                    onPreview={this.handledefaultcolumnImgsPreview}
                  >
                    {(this.state.columnImgsList && this.state.columnImgsList.length >= 1) || type === 'view'
                      ? null
                      : uploadButton}
                  </Upload>
                  <Modal
                    visible={this.state.previewcolumnImgsVisible}
                    footer={null}
                    onCancel={() => this.setState({previewcolumnImgsVisible: false})}
                  >
                    <img
                      alt="imgExample"
                      style={{width: '100%'}}
                      src={this.state.previewcolumnImgs}
                    />
                  </Modal>
                </div>
              )}
            </FormItem>
          </Col>
        </Row>
        <Card
          bordered
          hoverable
          size="small"
          bodyStyle={{ paddingBottom: 10 }}
          style={{ marginBottom: 20 }}
          title="专栏详细"
        >
          <div>
            {getFieldDecorator('columnDetails', {
              initialValue: BraftEditor.createEditorState(model.columnDetails),
            })(
              <BraftEditor
                className={styles.my_editor}
                placeholder="请输入专栏详细"
                onChange={editorState => {
                  // eslint-disable-next-line react/no-unused-state
                  this.setState({ editorState });
                }}
                extendControls={extendControls}
                {...inputCodeDisabledForView}
                {...editorProps}
              />
            )}
          </div>
        </Card>
      </Form>
    );
  }
}

/* eslint-disable no-class-assign */
//无更多的绑定， 请用 @Form.create() 注解替换
EditForm = Form.create({})(EditForm);
